package com.ita.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.ita.entity.User;
import com.ita.service.IUserService;
import com.ita.service.impl.UserServiceImpl;

/**
 * Servlet implementation class LoginServlet
 */
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private IUserService service=new UserServiceImpl();
    /**
     * @see HttpServlet#HttpServlet()
     */
    public LoginServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		login(request,response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		login(request,response);
	}
	private void login(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException{
		String userName=request.getParameter("userName");
		String password=request.getParameter("password");
		System.out.println("login name:"+userName);
		System.out.println("login password:"+password);
		
        User u=service.login(userName, password);
        if(u==null){
        	request.getRequestDispatcher("addUser.jsp").forward(request, response);
        }
        else{
        	request.setAttribute("userName", userName);
        	HttpSession session=request.getSession();
        	session.setAttribute("loginToken", u);
        	request.getRequestDispatcher("ContentServlet").forward(request, response);
        }
	}
}
